<template>
  <el-container>
    <el-aside width="258px">
      <side_tree v-if="isFinish" :data="roleList" :type="'role'" :default="groupItem.roleId" :typeName="'角色管理'" v-on:childtofather="childtofather"
      />
    </el-aside>
    <el-main>
      <el-col :span="24" class="flex flex-justify clear" style="border-bottom: 1px solid #eee;padding-bottom: 10px">
        <!--名称-->
        <h1>{{groupItem.roleName}}</h1>
        <!--按钮-->
        <el-col :span="18" class="flex flex-right">
          <!--按钮-->
          <el-col :span="18" class="flex flex-right">
            <el-button size="small" v-if="roleIdList.includes(14)" type="warning" @click="openModal" style="margin-right:20px"><i class="fa fa-plus"></i> 创建角色</el-button>
            <el-button v-if="roleIdList.includes(77)" size="small" type="primary" @click="save(false)" style="margin-right:20px" :disabled="groupItem.roleId===0">保存权限</el-button>
            <el-button v-if="roleIdList.includes(15)" size="small" @click="chosen('edit')" :disabled="!isUpdate" type="info">
              <i class="fa fa-edit"></i> 修改
            </el-button>
            <el-button size="small" type="danger" @click="del" v-if="roleIdList.includes(16)">
              <i class="fa fa-trash-o"></i>
              删除</el-button>
          </el-col>
        </el-col>
      </el-col>
      <!--部门信息 表单-->
      <el-form size="small" class="from-box" ref="groupItem" :rules="groupRules" :model="groupItem" label-width="80px">
        <el-col :span="24">
          <el-col :span="6">
            <el-form-item label="角色名称" prop="roleName">
              <el-input :readonly="isUpdate" v-model.trim="groupItem.roleName"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="上级角色" prop="parentList">
              <el-cascader :options="roleTree" change-on-select :props="{
                value: 'roleId',
                label: 'roleName',
            }" :show-all-levels="false" v-model="groupItem.parentList" style="width: 100%">
              </el-cascader>
            </el-form-item>
          </el-col> -->
        </el-col>
        <el-col :span="6" v-if="show">
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input :readonly="isUpdate" v-model.trim="groupItem.roleDesc"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="show">
          <el-button size="small" @click="chosen('save')" type="primary">
            <i class="fa fa-save"></i> 保存
          </el-button>
          <el-button size="small" @click="chosen('cancel')">
            <i class="fa fa-trash-o"></i> 取消</el-button>
        </el-col>
      </el-form>
      <el-col :span="24">
        <RoleCheck :data="roleData" :currentOperate="currentOperate" :currentId="groupItem.roleId" v-on:checkFinish="checkFinish"
        />
      </el-col>
    </el-main>
    <AddModal :addModal="addModal" @closeModal="closeModal" @finish="finish" />
  </el-container>
</template>

<script>
  import side_tree from "../aside";
  import RoleCheck from "./roleCheck.vue";
  import AddModal from "./addModal.vue";
  import {
    formCheck,
    deepClone
  } from "../../../lib/utils";
  import {
    roleManagement
  } from "../../../service/service_zbw";
  import {
    mapState,
    mapActions
  } from "vuex";
  export default {
    components: {
      RoleCheck,
      side_tree,
      AddModal
    },
    data() {
      return {
        judData: [{
          classname: '设备',
          id: '1',
          children: [{
            judName: '查看',
          }]
        }],
        roleData: {},
        //角色对应权限Id集合
        rolePowerList: [],
        //左侧选中节点数据
        copyGroupItem: {},
        groupItem: {
          roleId: 0,
          roleName: '',
          roleDesc: '',
          //parentList: []
        },
        groupRules: {
          roleName: [{
              required: true,
              message: '请输入角色名称',
              trigger: 'blur'
            },
            {
              max: 10,
              message: '长度不超过10个字符',
              trigger: 'blur'
            }
          ],
          roleDesc: [{
              message: '请输入角色描述',
              trigger: 'blur'
            },
            {
              max: 50,
              message: '长度不超过50个字符',
              trigger: 'blur'
            }
          ],
        },
        isUpdate: true,
        show: false,
        currentOperate: false,
        addModal: false,
        isFinish: true
      }
    },
    computed: {
      ...mapState({
        roleList: state => state.roleList,
        roleIdList: state => state.roleIdList,
        //roleTree: state => state.roleTree,
        rolePowerAll: state => state.rolePowerAll,
      }),
    },
    methods: {
      ...mapActions([
        'GetRoleList',
        //'GetRoleTree',
        'GetRolePowerList'
      ]),
      init() {
        this.groupItem = deepClone(this.roleList[0]);
        this.getRoleList(this.groupItem.roleId);
      },
      openModal() {
        this.addModal = true;
        this.isUpdate = true;
        this.show = false;
      },
      /**@function
       * 获取角色对应权限Id集合
       */
      async getRoleList(param) {;
        this.roleData = deepClone(this.rolePowerAll);
        let res = await roleManagement.getRoleList(param);
        if (res.success) {
          this.rolePowerList = res.obj;
          this.formatRolePower(this.rolePowerList);
        } else {
          this.rolePowerList = [];
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      },
      /**@function
       * 根据当前角色的权限Id集合去整理右侧可选树的选中情况
       */
      formatRolePower(val) {
        let arr = deepClone(val);
        for (let i = 0; i < arr.length; i++) {
          let flag = false;
          flag = this.ergodic(arr[i], this.roleData.menuPermissionList);
          if (!flag) {
            flag = this.ergodic(arr[i], this.roleData.flowPermissionList);
          }
          if (flag) {
            arr.splice(i, 1);
            i--;
          }
        }
      },
      ergodic(val, data) {
        let result = false;
        for (let i of data) {
          if (i.id === val) {
            i.checked = true;
            result = true;
            return result;
          } else if (i.children && i.children instanceof Array) {
            result = this.ergodic(val, i.children);
          }
        }
        return result;
      },
      /**@function
       * 保存修改后的角色权限
       */
      async save(status) {
        this.isUpdate = true;
        this.show = false;
        if (this.groupItem.roleId === 0) {
          return;
        }
        this.currentOperate = true;
        let arr = [];
        this.getPowerErgodic(arr, this.roleData.flowPermissionList);
        this.getPowerErgodic(arr, this.roleData.menuPermissionList);
        let param = {
          force: status,
          permissionList: arr,
          roleId: this.groupItem.roleId
        }
        let res = await roleManagement.save(param);
        if (res.success) {
          if (status) {
            this.GetRolePowerList();
          }
          this.$message({
            type: 'success',
            message: res.msg
          });
        } else {
          this.$confirm(`${res.msg}`, '询问', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            this.save(true);
          }).catch(() => {
            //TODO
          });
        }
      },
      getPowerErgodic(result, data) {
        for (let i of data) {
          if (i.checked) {
            result.push(i.id);
          }
          if (i.children && i.children instanceof Array) {
            this.getPowerErgodic(result, i.children);
          }
        }
      },
      /**@function
       * 完成操作触发
       */
      operateFinish() {
        this.GetRoleList();
      },
      /**
       * 编辑，保存，修改
       */
      async chosen(val) {
        if (val === 'edit') {
          this.copyGroupItem = deepClone(this.groupItem);
          this.isUpdate = !this.isUpdate;
          this.show = !this.show;
        } else if (val === 'save') {
          let flag = formCheck(this, 'groupItem');
          if (flag) {  
            let param = {
              roleDesc: this.groupItem.roleDesc,
              roleId: this.groupItem.roleId,
              roleName: this.groupItem.roleName,
              //parentId: this.groupItem.parentList[this.groupItem.parentList.length - 1]
            };
            let res = await roleManagement.update(param);
            if (res.success) {
              this.operateFinish();
              this.isUpdate = !this.isUpdate;
              this.show = !this.show;
              this.$message({
                message: res.msg,
                type: 'success'
              });
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          }
        } else if (val === 'cancel') {
          this.handleReset('groupItem');  
          this.groupItem = deepClone(this.copyGroupItem);
          this.isUpdate = !this.isUpdate;
          this.show = !this.show;
        }
      },
      /**
       * 删除
       */
      del() {
        this.isUpdate = true;
        this.show = false;
        this.$confirm('您确定要删除角色“' + this.groupItem.roleName + '”吗？', '询问', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.delete();
        }).catch(() => {
          //TODO
        });
      },
      async delete() {
        let param = this.groupItem.roleId;
        let res = await roleManagement.del(param);
        if (res.success) {
          let arr = deepClone(this.roleList);
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].roleId === this.groupItem.roleId) {
              arr.splice(i, 1);
            }
          }
          this.groupItem = deepClone(arr[0]);
          this.operateFinish();
          this.$message({
            message: res.msg,
            type: 'success'
          });
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      },
      childtofather(val) {
        this.groupItem = deepClone(val);
      },
      checkFinish(val) {
        this.currentOperate = false;
        this.roleData = deepClone(val);
      },
      /**@function
       * 新增完成
       */
      finish(val) {
        this.groupItem = deepClone(val);
        this.operateFinish();
      },
      /**@function
       * 关闭新增模态框
       */
      closeModal(val) {
        this.addModal = val;
      },
      /**
       * 清空表单
       */
      handleReset(name) {
        this.$refs[name].resetFields();
      }
    },
    watch: {
      "groupItem.roleId" (newval) {
        this.isUpdate = true;
        this.show = false;
        this.getRoleList(newval);
      }
    },
    mounted() {
      this.init();
    }
  }

</script>

<style scoped>
  h1 {
    width: 25%;
    font-weight: bold;
    color: #666666;
    font-size: 18px;
  }

  .role-title {
    background-color: ;
  }

</style>

